[[...path]].page.tsx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. import React, { useEffect } from 'react';
  2. import { isClient, pagePathUtils, pathUtils } from '@growi/core';
  3. import ExtensibleCustomError from 'extensible-custom-error';
  4. import {
  5. NextPage, GetServerSideProps, GetServerSidePropsContext,
  6. } from 'next';
  7. import dynamic from 'next/dynamic';
  8. import Head from 'next/head';
  9. import { useRouter } from 'next/router';
  10. // import { PageAlerts } from '~/components/PageAlert/PageAlerts';
  11. // import { PageComments } from '~/components/PageComment/PageComments';
  12. // import { useTranslation } from '~/i18n';
  13. import { isPopulated } from '~/interfaces/common';
  14. import { CrowiRequest } from '~/interfaces/crowi-request';
  15. // import { renderScriptTagByName, renderHighlightJsStyleTag } from '~/service/cdn-resources-loader';
  16. // import { useIndentSize } from '~/stores/editor';
  17. // import { useRendererSettings } from '~/stores/renderer';
  18. // import { EditorMode, useEditorMode, useIsMobile } from '~/stores/ui';
  19. import { IPageWithMeta } from '~/interfaces/page';
  20. import { ISidebarConfig } from '~/interfaces/sidebar-config';
  21. import { PageModel, PageDocument } from '~/server/models/page';
  22. import { serializeUserSecurely } from '~/server/models/serializers/user-serializer';
  23. import UserUISettings, { UserUISettingsDocument } from '~/server/models/user-ui-settings';
  24. import { useSWRxCurrentPage, useSWRxPageInfo } from '~/stores/page';
  25. import {
  26. usePreferDrawerModeByUser, usePreferDrawerModeOnEditByUser, useSidebarCollapsed, useCurrentSidebarContents, useCurrentProductNavWidth,
  27. } from '~/stores/ui';
  28. import loggerFactory from '~/utils/logger';
  29. // import { isUserPage, isTrashPage, isSharedPage } from '~/utils/path-utils';
  30. // import GrowiSubNavigation from '../client/js/components/Navbar/GrowiSubNavigation';
  31. // import GrowiSubNavigationSwitcher from '../client/js/components/Navbar/GrowiSubNavigationSwitcher';
  32. import { BasicLayout } from '../components/BasicLayout';
  33. import DisplaySwitcher from '../components/Page/DisplaySwitcher';
  34. // import { serializeUserSecurely } from '../server/models/serializers/user-serializer';
  35. // import PageStatusAlert from '../client/js/components/PageStatusAlert';
  36. import {
  37. useCurrentUser, useCurrentPagePath,
  38. useOwnerOfCurrentPage,
  39. useIsForbidden, useIsNotFound, useIsTrashPage, useShared, useShareLinkId, useIsSharedUser, useIsAbleToDeleteCompletely,
  40. useAppTitle, useSiteUrl, useConfidential, useIsEnabledStaleNotification,
  41. useIsSearchServiceConfigured, useIsSearchServiceReachable, useIsMailerSetup,
  42. useIsAclEnabled, useHasSlackConfig, useDrawioUri, useHackmdUri, useMathJax,
  43. useNoCdn, useEditorConfig, useCsrfToken, useIsSearchScopeChildrenAsDefault, useCurrentPageId, useCurrentPathname, useIsSlackConfigured,
  44. } from '../stores/context';
  45. import { CommonProps, getServerSideCommonProps, useCustomTitle } from './commons';
  46. // import { useCurrentPageSWR } from '../stores/page';
  47. const logger = loggerFactory('growi:pages:all');
  48. const { isPermalink: _isPermalink, isUsersHomePage, isTrashPage: _isTrashPage } = pagePathUtils;
  49. const { removeHeadingSlash } = pathUtils;
  50. const IdenticalPathPage = (): JSX.Element => {
  51. const IdenticalPathPage = dynamic(() => import('../components/IdenticalPathPage').then(mod => mod.IdenticalPathPage), { ssr: false });
  52. return <IdenticalPathPage />;
  53. };
  54. type Props = CommonProps & {
  55. currentUser: string,
  56. pageWithMetaStr: string,
  57. // pageUser?: any,
  58. // redirectTo?: string;
  59. // redirectFrom?: string;
  60. // shareLinkId?: string;
  61. isIdenticalPathPage?: boolean,
  62. isForbidden: boolean,
  63. isNotFound: boolean,
  64. // isAbleToDeleteCompletely: boolean,
  65. isSearchServiceConfigured: boolean,
  66. isSearchServiceReachable: boolean,
  67. isSearchScopeChildrenAsDefault: boolean,
  68. isSlackConfigured: boolean,
  69. // isMailerSetup: boolean,
  70. isAclEnabled: boolean,
  71. // hasSlackConfig: boolean,
  72. // drawioUri: string,
  73. // hackmdUri: string,
  74. // mathJax: string,
  75. // noCdn: string,
  76. // highlightJsStyle: string,
  77. // isAllReplyShown: boolean,
  78. // isContainerFluid: boolean,
  79. // editorConfig: any,
  80. // isEnabledStaleNotification: boolean,
  81. // isEnabledLinebreaks: boolean,
  82. // isEnabledLinebreaksInComments: boolean,
  83. // adminPreferredIndentSize: number,
  84. // isIndentSizeForced: boolean,
  85. // UI
  86. userUISettings: UserUISettingsDocument | null
  87. // Sidebar
  88. sidebarConfig: ISidebarConfig,
  89. };
  90. const GrowiPage: NextPage<Props> = (props: Props) => {
  91. // const { t } = useTranslation();
  92. const router = useRouter();
  93. const UnsavedAlertDialog = dynamic(() => import('./UnsavedAlertDialog'), { ssr: false });
  94. const { data: currentUser } = useCurrentUser(props.currentUser != null ? JSON.parse(props.currentUser) : null);
  95. // commons
  96. useAppTitle(props.appTitle);
  97. useSiteUrl(props.siteUrl);
  98. // useEditorConfig(props.editorConfig);
  99. useConfidential(props.confidential);
  100. useCsrfToken(props.csrfToken);
  101. // UserUISettings
  102. usePreferDrawerModeByUser(props.userUISettings?.preferDrawerModeByUser ?? props.sidebarConfig.isSidebarDrawerMode);
  103. usePreferDrawerModeOnEditByUser(props.userUISettings?.preferDrawerModeOnEditByUser);
  104. useSidebarCollapsed(props.userUISettings?.isSidebarCollapsed ?? props.sidebarConfig.isSidebarClosedAtDockMode);
  105. useCurrentSidebarContents(props.userUISettings?.currentSidebarContents);
  106. useCurrentProductNavWidth(props.userUISettings?.currentProductNavWidth);
  107. // page
  108. useCurrentPagePath(props.currentPathname);
  109. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  110. useIsForbidden(props.isForbidden);
  111. useIsNotFound(props.isNotFound);
  112. // useIsTrashPage(_isTrashPage(props.currentPagePath));
  113. // useShared();
  114. // useShareLinkId(props.shareLinkId);
  115. // useIsAbleToDeleteCompletely(props.isAbleToDeleteCompletely);
  116. useIsSharedUser(false); // this page cann't be routed for '/share'
  117. // useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  118. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  119. useIsSearchServiceReachable(props.isSearchServiceReachable);
  120. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  121. useIsSlackConfigured(props.isSlackConfigured);
  122. // useIsMailerSetup(props.isMailerSetup);
  123. useIsAclEnabled(props.isAclEnabled);
  124. // useHasSlackConfig(props.hasSlackConfig);
  125. // useDrawioUri(props.drawioUri);
  126. // useHackmdUri(props.hackmdUri);
  127. // useMathJax(props.mathJax);
  128. // useNoCdn(props.noCdn);
  129. // useIndentSize(props.adminPreferredIndentSize);
  130. // useRendererSettings({
  131. // isEnabledLinebreaks: props.isEnabledLinebreaks,
  132. // isEnabledLinebreaksInComments: props.isEnabledLinebreaksInComments,
  133. // adminPreferredIndentSize: props.adminPreferredIndentSize,
  134. // isIndentSizeForced: props.isIndentSizeForced,
  135. // });
  136. // const { data: editorMode } = useEditorMode();
  137. let pageWithMeta: IPageWithMeta | undefined;
  138. if (props.pageWithMetaStr != null) {
  139. pageWithMeta = JSON.parse(props.pageWithMetaStr) as IPageWithMeta;
  140. }
  141. useCurrentPageId(pageWithMeta?.data._id);
  142. useSWRxCurrentPage(undefined, pageWithMeta?.data); // store initial data
  143. useSWRxPageInfo(pageWithMeta?.data._id, undefined, pageWithMeta?.meta); // store initial data
  144. useCurrentPagePath(pageWithMeta?.data.path);
  145. useCurrentPathname(props.currentPathname);
  146. // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  147. useEffect(() => {
  148. if (isClient() && window.location.pathname !== props.currentPathname) {
  149. router.replace(props.currentPathname, undefined, { shallow: true });
  150. }
  151. }, [props.currentPathname, router]);
  152. const classNames: string[] = [];
  153. // switch (editorMode) {
  154. // case EditorMode.Editor:
  155. // classNames.push('on-edit', 'builtin-editor');
  156. // break;
  157. // case EditorMode.HackMD:
  158. // classNames.push('on-edit', 'hackmd');
  159. // break;
  160. // }
  161. // if (props.isContainerFluid) {
  162. // classNames.push('growi-layout-fluid');
  163. // }
  164. // if (page == null) {
  165. // classNames.push('not-found-page');
  166. // }
  167. return (
  168. <>
  169. <Head>
  170. {/*
  171. {renderScriptTagByName('drawio-viewer')}
  172. {renderScriptTagByName('mathjax')}
  173. {renderScriptTagByName('highlight-addons')}
  174. {renderHighlightJsStyleTag(props.highlightJsStyle)}
  175. */}
  176. </Head>
  177. {/* <BasicLayout title={useCustomTitle(props, t('GROWI'))} className={classNames.join(' ')}> */}
  178. <BasicLayout title={useCustomTitle(props, 'GROWI')} className={classNames.join(' ')}>
  179. <header className="py-0">
  180. {/* <GrowiSubNavigation /> */}
  181. GrowiSubNavigation
  182. </header>
  183. <div className="d-edit-none">
  184. {/* <GrowiSubNavigationSwitcher /> */}
  185. GrowiSubNavigationSwitcher
  186. </div>
  187. <div id="grw-subnav-sticky-trigger" className="sticky-top"></div>
  188. <div id="grw-fav-sticky-trigger" className="sticky-top"></div>
  189. <div id="main" className={`main ${isUsersHomePage(props.currentPathname) && 'user-page'}`}>
  190. <div className="row">
  191. <div className="col">
  192. <div id="content-main" className="content-main grw-container-convertible">
  193. { props.isIdenticalPathPage && <IdenticalPathPage /> }
  194. { !props.isIdenticalPathPage && (
  195. <>
  196. {/* <PageAlerts /> */}
  197. PageAlerts<br />
  198. { props.isForbidden
  199. ? <>ForbiddenPage</>
  200. : <DisplaySwitcher />
  201. }
  202. <div id="page-editor-navbar-bottom-container" className="d-none d-edit-block"></div>
  203. {/* <PageStatusAlert /> */}
  204. PageStatusAlert
  205. </>
  206. ) }
  207. </div>
  208. </div>
  209. {/* <div className="col-xl-2 col-lg-3 d-none d-lg-block revision-toc-container">
  210. <div id="revision-toc" className="revision-toc mt-3 sps sps--abv" data-sps-offset="123">
  211. <div id="revision-toc-content" className="revision-toc-content"></div>
  212. </div>
  213. </div> */}
  214. </div>
  215. </div>
  216. <footer>
  217. {/* <PageComments /> */}
  218. PageComments
  219. </footer>
  220. <UnsavedAlertDialog />
  221. </BasicLayout>
  222. </>
  223. );
  224. };
  225. function getPageIdFromPathname(currentPathname: string): string | null {
  226. return _isPermalink(currentPathname) ? removeHeadingSlash(currentPathname) : null;
  227. }
  228. class MultiplePagesHitsError extends ExtensibleCustomError {
  229. pagePath: string;
  230. constructor(pagePath: string) {
  231. super(`MultiplePagesHitsError occured by '${pagePath}'`);
  232. this.pagePath = pagePath;
  233. }
  234. }
  235. async function getPageData(context: GetServerSidePropsContext, props: Props): Promise<IPageWithMeta|null> {
  236. const req: CrowiRequest = context.req as CrowiRequest;
  237. const { crowi } = req;
  238. const { revisionId } = req.query;
  239. const Page = crowi.model('Page') as PageModel;
  240. const { pageService } = crowi;
  241. const { currentPathname } = props;
  242. const pageId = getPageIdFromPathname(currentPathname);
  243. const isPermalink = _isPermalink(currentPathname);
  244. const { user } = req;
  245. // check whether the specified page path hits to multiple pages
  246. if (!isPermalink) {
  247. const count = await Page.countByPathAndViewer(currentPathname, user, null, true);
  248. if (count > 1) {
  249. throw new MultiplePagesHitsError(currentPathname);
  250. }
  251. }
  252. const result: IPageWithMeta = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
  253. const page = result?.data as unknown as PageDocument;
  254. // populate
  255. if (page != null) {
  256. page.initLatestRevisionField(revisionId);
  257. await page.populateDataToShowRevision();
  258. }
  259. return result;
  260. }
  261. async function injectRoutingInformation(context: GetServerSidePropsContext, props: Props, pageWithMeta: IPageWithMeta|null): Promise<void> {
  262. const req: CrowiRequest = context.req as CrowiRequest;
  263. const { crowi } = req;
  264. const Page = crowi.model('Page') as PageModel;
  265. const { currentPathname } = props;
  266. const pageId = getPageIdFromPathname(currentPathname);
  267. const isPermalink = _isPermalink(currentPathname);
  268. const page = pageWithMeta?.data;
  269. if (props.isIdenticalPathPage) {
  270. // TBD
  271. }
  272. else if (page == null) {
  273. props.isNotFound = true;
  274. // check the page is forbidden or just does not exist.
  275. const count = isPermalink ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
  276. props.isForbidden = count > 0;
  277. }
  278. else {
  279. // /62a88db47fed8b2d94f30000 ==> /path/to/page
  280. if (isPermalink && page.isEmpty) {
  281. props.currentPathname = page.path;
  282. }
  283. // /path/to/page ==> /62a88db47fed8b2d94f30000
  284. if (!isPermalink && !page.isEmpty) {
  285. const isToppage = pagePathUtils.isTopPage(props.currentPathname);
  286. if (!isToppage) {
  287. props.currentPathname = `/${page._id}`;
  288. }
  289. }
  290. }
  291. }
  292. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  293. // const req: CrowiRequest = context.req as CrowiRequest;
  294. // const { crowi } = req;
  295. // const UserModel = crowi.model('User');
  296. // if (isUserPage(props.currentPagePath)) {
  297. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  298. // if (user != null) {
  299. // props.pageUser = JSON.stringify(user.toObject());
  300. // }
  301. // }
  302. // }
  303. async function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): Promise<void> {
  304. const req: CrowiRequest = context.req as CrowiRequest;
  305. const { crowi } = req;
  306. const {
  307. appService, searchService, configManager, aclService, slackNotificationService, mailService,
  308. } = crowi;
  309. props.isSearchServiceConfigured = searchService.isConfigured;
  310. props.isSearchServiceReachable = searchService.isReachable;
  311. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  312. props.isSlackConfigured = crowi.slackIntegrationService.isSlackConfigured;
  313. // props.isMailerSetup = mailService.isMailerSetup;
  314. props.isAclEnabled = aclService.isAclEnabled();
  315. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  316. // props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  317. // props.hackmdUri = configManager.getConfig('crowi', 'app:hackmdUri');
  318. // props.mathJax = configManager.getConfig('crowi', 'app:mathJax');
  319. // props.noCdn = configManager.getConfig('crowi', 'app:noCdn');
  320. // props.highlightJsStyle = configManager.getConfig('crowi', 'customize:highlightJsStyle');
  321. // props.isAllReplyShown = configManager.getConfig('crowi', 'customize:isAllReplyShown');
  322. // props.isContainerFluid = configManager.getConfig('crowi', 'customize:isContainerFluid');
  323. // props.isEnabledStaleNotification = configManager.getConfig('crowi', 'customize:isEnabledStaleNotification');
  324. // props.isEnabledLinebreaks = configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks');
  325. // props.isEnabledLinebreaksInComments = configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments');
  326. // props.editorConfig = {
  327. // upload: {
  328. // image: crowi.fileUploadService.getIsUploadable(),
  329. // file: crowi.fileUploadService.getFileUploadEnabled(),
  330. // },
  331. // };
  332. // props.adminPreferredIndentSize = configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize');
  333. // props.isIndentSizeForced = configManager.getConfig('markdown', 'markdown:isIndentSizeForced');
  334. props.sidebarConfig = {
  335. isSidebarDrawerMode: configManager.getConfig('crowi', 'customize:isSidebarDrawerMode'),
  336. isSidebarClosedAtDockMode: configManager.getConfig('crowi', 'customize:isSidebarClosedAtDockMode'),
  337. };
  338. }
  339. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  340. const req: CrowiRequest = context.req as CrowiRequest;
  341. const { user } = req;
  342. const result = await getServerSideCommonProps(context);
  343. // check for presence
  344. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  345. if (!('props' in result)) {
  346. throw new Error('invalid getSSP result');
  347. }
  348. const props: Props = result.props as Props;
  349. let pageWithMeta;
  350. try {
  351. pageWithMeta = await getPageData(context, props);
  352. props.pageWithMetaStr = JSON.stringify(pageWithMeta);
  353. }
  354. catch (err) {
  355. if (err instanceof MultiplePagesHitsError) {
  356. props.isIdenticalPathPage = true;
  357. }
  358. else {
  359. throw err;
  360. }
  361. }
  362. injectRoutingInformation(context, props, pageWithMeta);
  363. injectServerConfigurations(context, props);
  364. if (user != null) {
  365. props.currentUser = JSON.stringify(user);
  366. }
  367. // UI
  368. const userUISettings = user == null ? null : await UserUISettings.findOne({ user: user._id }).exec();
  369. props.userUISettings = JSON.parse(JSON.stringify(userUISettings));
  370. return {
  371. props,
  372. };
  373. };
  374. export default GrowiPage;